<?php
define('PATH',dirname(__FILE__).'/');
define('SURL',$_SERVER['PHP_SELF']);
session_start();
if(!file_exists(PATH.'config.php')){
	include(PATH.'install.php');
	exit;
}
include_once PATH.'config.php';
mysql_connect(CFG_MYSQL_SERVER,CFG_MYSQL_USERNAME,CFG_MYSQL_PASSWORD);
mysql_select_db(CFG_MYSQL_DBNAME);
$reqCmd='home';
isset($_REQUEST['cmd']) and $reqCmd=$_REQUEST['cmd'];
if($reqCmd<>'login' and $reqCmd<>'reg' and $reqCmd<>'picraw'){
	if($_COOKIE['userId'] and $_COOKIE['userHash']){
		$usrHash=md5($_COOKIE['userHash']);
		$dbreq=mysql_query("SELECT * FROM `pw_users` WHERE `id`=".(int)$_COOKIE['userId']." AND `hash`='{$usrHash}';");
		if(!$dbreq or !$dbres=mysql_fetch_array($dbreq)){
			header('Location: '.SURL.'?cmd=login');
			exit;
		}else{
			$_SERVER['userId']=$dbres['id'];
			$_SERVER['userName']=$dbres['name'];
		}
		mysql_free_result($dbreq);
	}else{
		header('Location: '.SURL.'?cmd=login');
		exit;
	}
}

switch($reqCmd){
	case 'login':
		if(isset($_REQUEST['act']) and $_REQUEST['act']=='login'){
			$logedIn=FALSE;
			if(!preg_match("~^[A-Za-z]\w{2,17}$~",$_REQUEST['username'])){
				$errInfo="Invailed username.";
			}elseif(isset($_REQUEST['nojs'])){
				$pswHash=md5($_REQUEST['password']);
				$dbreq=mysql_query("SELECT `id` FROM `pw_users` WHERE `name`='{$_REQUEST['username']}' AND `psw`='{$pswHash}';");
				if($dbres=mysql_fetch_array($dbreq))
					$logedIn=TRUE;
				else
					$errInfo='Username or password incorrect.';
			}elseif(!isset($_SESSION['randomCode'])){
				$errInfo='Page experied or Cookies not enabled.';
			}else{
				$dbreq=mysql_query("SELECT `id`,`psw` FROM `pw_users` WHERE `name`='{$_REQUEST['username']}';");
				if($dbres=mysql_fetch_array($dbreq)){
					if(md5($dbres['psw'].$_SESSION['randomCode'])==$_REQUEST['password'])
						$logedIn=TRUE;
					else
						$errInfo='Username or password incorrect.';
				}
				unset($_SESSION['randomCode']);
			}
			mysql_free_result($dbreq);
			if(!$logedIn){
				include(PATH.'template/login.fail.php');
			}else{
				$usrHash=md5(time().mt_rand(0,99999999).$_REQUEST['username'].$_REQUEST['password']);
				mysql_query("UPDATE `pw_users` SET `hash`='".md5($usrHash)."' WHERE `id`={$dbres['id']};");
				setcookie('userId',$dbres['id'],time()+2592000);
				setcookie('userHash',$usrHash,time()+2592000);
				include(PATH.'template/login.loged.php');
			}
		}elseif(isset($_REQUEST['nojs'])){
			include(PATH.'template/login.form.normal.php');
		}else{
			$psfrs='1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
			$randomCode='';
			for($i=0;$i<20;$i++)
				$randomCode.=$psfrs[mt_rand(0,63)];
			$_SESSION['randomCode']=$randomCode;
			include(PATH.'template/login.form.jssafe.php');
		}
		break;
	case 'reg':
		if(isset($_REQUEST['act']) and $_REQUEST['act']=='done'){
			$errInfo='';
			if(!preg_match("~^[A-Za-z]\w{2,17}$~",$_REQUEST['username'])){
				$errInfo='Username invailed.';
			}elseif($_REQUEST['password']<>$_REQUEST['password2']){
				$errInfo='Password not match.';
			}elseif(!preg_match('~^[^\\\'"]{5,18}$~',$_REQUEST['password'])){
				$errInfo='Password invailed.';
			}else{
				$dbreq=mysql_query("SELECT `id` FROM `pw_users` WHERE `name`='{$_REQUEST['username']}';");
				if(mysql_fetch_array($dbreq))
					$errInfo='Username already exists.';
				mysql_free_result($dbreq);
			}
			if(!$errInfo){
				mysql_query("INSERT INTO `pw_users`(`name`, `psw`) VALUES('{$_REQUEST['username']}', '".md5($_REQUEST['password'])."');");
				include(PATH.'template/reg.copmlate.php');
			}else{
				include(PATH.'template/reg.fail.php');
			}
		}else{
			include(PATH.'template/reg.form.php');
		}
		break;
	case 'logout':
		mysql_query("UPDATE `pw_users` SET `hash`='' WHERE `id`={$_SERVER['userId']};");
		setcookie('userId','',time()-3600);
		setcookie('userHash','',time()-3600);
		include(PATH.'template/logout.php');
		break;
	case 'editprofile':
		if(isset($_REQUEST['act']) and $_REQUEST['act']=='done'){
			$errInfo='';
			$changes=0;
			if(isset($_REQUEST['username']) and $_REQUEST['username'] and $_REQUEST['username']<>$_SERVER['userName']){
				$changes+=1;
				if(!preg_match("~^[A-Za-z]\w{2,17}$~",$_REQUEST['username']))
					$errInfo='Username invailed.';
			}
			if(isset($_REQUEST['password']) and $_REQUEST['password']){
				$changes+=2;
				if($_REQUEST['password']<>$_REQUEST['password2'])
					$errInfo='Password not match.';
				elseif(!preg_match('~^[^\\\'"]{5,18}$~',$_REQUEST['password']))
					$errInfo='Password Invailed.';
			}
			$changes or $errInfo='No changes updated.';
			if(!$errInfo){
				$dbq=mysql_query("SELECT `psw` FROM `pw_users` WHERE `id`={$_SERVER['userId']};");
				if($dbr=mysql_fetch_array($dbq))
					$dbr['psw']<>md5($_REQUEST['opassword']) and $errInfo='Incorrect old password.';
				else
					$errInfo='User not found in the database.';
				mysql_free_result($dbq);
			}
			if(!$errInfo){
				switch($changes){
					case 0:
						$info='No changes updated.';
						break;
					case 1:
						$info='Username updated, this change will apply when you logout.';
						mysql_query("UPDATE `pw_users` SET `name`='{$_REQUEST['username']}' WHERE `id`={$_SERVER['userId']}");
						break;
					case 2:
						$info='Password updated, this change will apply when you logout.';
						mysql_query("UPDATE `pw_users` SET `psw`='".md5($_REQUEST['password'])."' WHERE `id`={$_SERVER['userId']}");
						break;
					case 3:
						$info='Username and password updated. changes will apply when you logout.';
						mysql_query("UPDATE `pw_users` SET `name`='{$_REQUEST['username']}', `psw`='".md5($_REQUEST['password'])."' WHERE `id`={$_SERVER['userId']}");
						break;
					default:
						$info='Error: Unexcepted change way received.';
						break;
				}
				include(PATH.'template/editprofile.done.php');
			}else{
				include(PATH.'template/editprofile.fail.php');
			}
		}else{
			include(PATH.'template/editprofile.form.php');
		}
		break;
	case 'home':
		$contents=array();
		$currentPage=isset($_REQUEST['page'])?(int)$_REQUEST['page']:1;
		$dbq=mysql_query("SELECT `id` FROM `pw_piclog` WHERE `belong`={$_SERVER['userId']};");
		$totalEntries=$dbq?mysql_num_rows($dbq):0;
		mysql_free_result($dbq);
		$totalPage=(int)($totalEntries/20);
		$totalEntries%20 and $totalPage+=1;
		$totalPage<1 and $totalPage=1;
		$currentPage>$totalPage and $currentPage=$totalPage;
		$entryOffset=(int)$currentPage*20-20;
		$dbq=mysql_query("SELECT * FROM `pw_piclog` WHERE `belong`={$_SERVER['userId']} ORDER BY `id` DESC LIMIT {$entryOffset},20");
		while($dbq and $dbr=mysql_fetch_array($dbq)){
			$contents[]=array($dbr['id'],$dbr['rhash'],$dbr['fpath']);
		}
		mysql_free_result($dbq);
		include(PATH.'template/home.php');
		break;
	case 'delete':
		$picId=(int)$_REQUEST['pid'];
		$dbq=mysql_query("SELECT `fpath` FROM `pw_piclog` WHERE `id`={$picId} AND `belong`={$_SERVER['userId']};");
		if($dbq and $dbr=mysql_fetch_array($dbq)){
			mysql_query("DELETE FROM `pw_piclog` WHERE `id`={$picId};");
			unlink(PATH.$dbr['fpath']);
			include(PATH.'template/delete.done.php');
		}else{
			include(PATH.'template/delete.fail.php');
		}
		mysql_free_result($dbq);
		break;
	case 'upload':
		if(isset($_REQUEST['act']) and $_REQUEST['act']=='done'){
			$uploadResult=array();
			for($i=0;isset($_FILES['picFiles']['name'][$i]);$i++){
				if(!$_FILES['picFiles']['error'][$i] and $_FILES['picFiles']['name'][$i]){
					if($_FILES['picFiles']['size'][$i]>=1024 and $_FILES['picFiles']['size'][$i]<=2097152){
						$fileExName=strtolower(substr($_FILES['picFiles']['name'][$i],-4));
						switch($fileExName){
							case '.jpg':
								$saveAllowed=TRUE;
								break;
							case '.png':
								$saveAllowed=TRUE;
								break;
							case '.gif':
								$saveAllowed=TRUE;
								break;
							default:
								$saveAllowed=FALSE;
								break;
						}
						$saveAllowed=($saveAllowed and is_array(getimagesize($_FILES['picFiles']['tmp_name'][$i])));
						if($saveAllowed){
							$picSavePath='image/'.date('Y').'/'.date('m').'/'.md5('PictureFile: '.mt_rand(0,99999999).time().$_SERVER['userName']).$fileExName;
							$picHashName=md5(mt_rand(0,99999999).$_FILES['picFiles']['name'][$i].time().$_SERVER['userName']);
							mysql_query("INSERT INTO `pw_piclog`(`belong`, `rhash`, `fpath`) VALUES({$_SERVER['userId']}, '{$picHashName}', '{$picSavePath}');");
							is_dir(dirname(PATH.$picSavePath)) or mkdir(dirname(PATH.$picSavePath),0755,TRUE);
							move_uploaded_file($_FILES['picFiles']['tmp_name'][$i],PATH.$picSavePath);
							$uploadResult[]='Uploaded: '.$_FILES['picFiles']['name'][$i];
						}
					}
				}
			}
			if(count($uploadResult)){
				include_once PATH.'template/upload.done.php';
			}else{
				include_once PATH.'template/upload.fail.php';
			}
		}else{
			include(PATH.'template/upload.form.php');
		}
		break;
	case 'picraw':
		$picId=isset($_REQUEST['pi'])?(int)$_REQUEST['pi']:0;
		$resize=FALSE;
		if(isset($_REQUEST['resize']) and preg_match('~^(\d+)x(\d+)$~i',$_REQUEST['resize'],$matches)){
			if($matches[1]>19 and $matches[2]>19 and $matches[1]<2000 and $matches[2]<2000){
				$resize=array($matches[1],$matches[2]);
			}
		}
		if(!$picId or !preg_match('~^[0-9a-z]{32}$~',$_REQUEST['ph'])){
			$resize=FALSE;
			$picFInfo=array('template/notfound.png',1);
		}else{
			$dbq=mysql_query("SELECT `fpath` FROM `pw_piclog` WHERE `rhash`='{$_REQUEST['ph']}' AND `id`={$picId};");
			if($dbr=mysql_fetch_array($dbq)){
				$picFExName=strtolower(substr($dbr['fpath'],-3));
				switch($picFExName){
					case 'jpg':
						$picMimeType=0;
						break;
					case 'png':
						$picMimeType=1;
						break;
					case 'gif':
						$picMimeType=2;
						break;
				}
				$picFInfo=array($dbr['fpath'],$picMimeType);
			}else{
				$picFInfo=array('template/notfound.png',1);
				$resize=FALSE;
			}
			mysql_free_result($dbq);
			if($resize){
				$picTmbFName='thumb'.substr($picFInfo[0],0,strlen($picFInfo[0])-4).'_'.$resize[0].'x'.$resize[1].'.jpg';
				is_dir(dirname(PATH.$picTmbFName)) or mkdir(dirname(PATH.$picTmbFName),0755,TRUE);
				if(!file_exists(PATH.$picTmbFName)){
					switch($picFInfo[1]){
						case 0:
							$picRes=imagecreatefromjpeg(PATH.$picFInfo[0]);
							break;
						case 1:
							$picRes=imagecreatefrompng(PATH.$picFInfo[0]);
							break;
						case 2:
							$picRes=imagecreatefromgif(PATH.$picFInfo[0]);
							break;
					}
					$picTmbRes=imagecreatetruecolor($resize[0],$resize[1]);
					imagecopyresized($picTmbRes,$picRes,0,0,0,0,$resize[0],$resize[1],imagesx($picRes),imagesy($picRes));
					imagejpeg($picTmbRes,PATH.$picTmbFName);
				}
				$picFInfo=array($picTmbFName,0);
			}
			switch($picFInfo[1]){
				case 0:
					header('Content-Type: image/jpeg');
					break;
				case 1:
					header('Content-Type: image/png');
					break;
				case 2:
					header('Content-Type: image/gif');
					break;
			}
			$picfp=fopen(PATH.$picFInfo[0],'rb');
			while(connection_status()==0 and !feof($picfp)){
				echo fread($picfp,8192);
				flush();
			}
			fclose($picfp);
		break;
	}
}
